package com.shiyi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpSession;
import java.util.Locale;

/**
 * @author wangzhanshuai
 * @date 2021/1/23 6:34 下午
 * @since 1.0
 */
@Controller
public class LocalResolverController {

    /**
     * 使用自定义国际化解析器来处理国际化
     * @param localStr
     * @param locale
     * @return
     */
    @RequestMapping("/i18n")
    public String testLocalResolver(@RequestParam(value = "locale", required = false) String localStr, Locale locale) {
        System.out.println(localStr);
        System.out.println(locale.getLanguage());
        return "login";
    }

    /**
     * 使用session来处理国际化
     * @param localStr
     * @param locale
     * @param httpSession
     * @return
     */
    @RequestMapping("/i18n2")
    public String testLocalResolver2(@RequestParam(value = "locale", required = false) String localStr, Locale locale, HttpSession httpSession) {
        System.out.println(this.getClass().getName() + "-----" + localStr);

        Locale locale1 = locale;
        if(StringUtils.hasText(localStr)) {
            String[] split = localStr.split("_");
            if(split.length == 2) {
                locale1 =  new Locale(split[0], split[1]);
            }
        }

        httpSession.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE", locale1);
        return "login";
    }

    /**
     * 使用拦截器来处理国际化
     * LocaleChangeInterceptor
     * @return
     */
    @RequestMapping("/i18n3")
    public String testLocalResolver3(@RequestParam(value = "locale", required = false) String localStr) {
        System.out.println(this.getClass().getName() + "-----testLocalResolver3" + localStr);
        return "login";
    }
}
